package com.hngy.educationaladministration.utils;

import com.hngy.educationaladministration.entity.FutureWeather;
import com.hngy.educationaladministration.entity.Weather_Result_Realtime;
import com.hngy.educationaladministration.service.WeatherService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList;

/**
 * @author Deng JunHao
 * @date 2021/04/07 11:36
 * @description：天气查询
 **/
@Service
public class WeatherUtil {

    /**
     * 请求真实ip ， 通过request请求获取到的IP地址是不够严谨的，
     * 也许该IP地址经历了重重的反向代理早已经不是浏览页面的浏览者本人所在城市的IP地址了。
     * 所以通过一段代码先对IP进行解析，以方便获取他的真实IP地址。
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;

    }

    /**
     * 根据IP获取所在城市的名称
     *
     * @param IP
     * @return
     */
    public static String getCityByIp(String IP) {
        String City = null;
        String jsonstr = null;
        String url = "http://apis.juhe.cn/ip/ipNew";
        String srtVlaue = "ip=" + IP + "&key=022287affefd4e498740d2d107efbe4c";
        jsonstr = HttpGetPost.sendGet(url, srtVlaue);
        if (jsonstr.equals("请求超时")) {
            return "获取城市名称失败";
        }
        JSONObject json = JSONObject.fromObject(jsonstr);
        String resultcode = (String) json.get("resultcode");
        if (resultcode.equals("200")) {//接口請求成功
            JSONObject result = (JSONObject) json.get("result");
            City = (String) result.get("City");
        } else {
            City = "所在城市获取失败";
        }
        if (City.contains("市")) {
            City = City.substring(0, 2);//只截取前两位汉字
        }
        System.out.println("根据IP:" + IP + "获取城市名称为:" + City);
        return City;
    }

    /**
     * 根据城市名称获取该城市的天气状况
     *
     * @param City
     * @return
     */
    public static JSONObject getWeatherReason(String City) {
        String jsonStr = "";
        String strUrl = "http://apis.juhe.cn/simpleWeather/query";
        String srtVlaue = "city=" + City + "&key=93e7573d94a0b85b2ac38ded5aef41e0";
        jsonStr = HttpGetPost.sendGet(strUrl, srtVlaue);
        JSONObject json = JSONObject.fromObject(jsonStr);
        JSONObject result = json.getJSONObject("result");
        return result;
    }

    public static FutureWeather getFutureWeather(JSONObject result) {
        JSONArray future = result.getJSONArray("future");
        ArrayList<FutureWeather> collection = (ArrayList<FutureWeather>) JSONArray.toCollection(future, FutureWeather.class);
        FutureWeather futureWeather = collection.get(1);
        return futureWeather;
    }

    public static Weather_Result_Realtime getTodayWeather(JSONObject result) {
        //当天天气
        Weather_Result_Realtime weatherresultrealtime = new Weather_Result_Realtime();
        weatherresultrealtime.setCity(result.getString("city"));
        JSONObject realtime = result.getJSONObject("realtime");
        weatherresultrealtime.setInfo(realtime.getString("info"));
        weatherresultrealtime.setTemperature(realtime.getString("temperature"));
        weatherresultrealtime.setHumidity(realtime.getString("humidity"));
        weatherresultrealtime.setDirect(realtime.getString("direct"));
        weatherresultrealtime.setPower(realtime.getString("power"));
        weatherresultrealtime.setAqi(realtime.getString("aqi"));

        return weatherresultrealtime;
    }

    public static void setWeatherForController(HttpServletRequest request) {
        //获取系统时间和天气
        DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        LocalDate now1 = LocalDate.now();
        String format = dateTimeFormatter3.format(now1);
        request.getSession().setAttribute("NowDate", format);
        //获取真实ip，用于天气查询，设置天气
        //String ipAddress =WeatherUtil.getIpAddr(request); 这两个一样
        String ipAddress = HttpGetPost.getClientIp(request);
        WeatherService weatherService = ApplicationContextHolder.getBean(WeatherService.class);
        JSONObject weatherReason = weatherService.getWeather(ipAddress);
        //今天天气
        Weather_Result_Realtime todayWeather = WeatherUtil.getTodayWeather(weatherReason);
        request.getSession().setAttribute("city", todayWeather.getCity());
        String temperature = todayWeather.getTemperature();
        String info = todayWeather.getInfo();
        String humidity = todayWeather.getHumidity();
        String direct = todayWeather.getDirect();
        String power = todayWeather.getPower();
        String aqi = todayWeather.getAqi();
        request.getSession().setAttribute("temperature", temperature);
        request.getSession().setAttribute("info", info);
        request.getSession().setAttribute("humidity", humidity);
        request.getSession().setAttribute("direct", direct);
        request.getSession().setAttribute("power", power);
        request.getSession().setAttribute("aqi", aqi);

        FutureWeather futureWeather = WeatherUtil.getFutureWeather(weatherReason);
        String futureWeatherDate = futureWeather.getDate();
        String futureWeatherTemperature = futureWeather.getTemperature();
        String futureWeatherWeather = futureWeather.getWeather();
        request.getSession().setAttribute("futureWeatherDate", futureWeatherDate);
        request.getSession().setAttribute("futureWeatherTemperature", futureWeatherTemperature);
        request.getSession().setAttribute("futureWeatherWeather", futureWeatherWeather);
        //获取系统时间和天气
    }
}
